<?php


namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;

class WxUser extends Homebase
{
    protected $openid;
    protected $memberInfo;
    protected $memberId;
    protected $role;
    protected $noRule = ['getBusinessList',
        'getOperateCateList',
        'getBusinessDetail',
        'getGoodsList',
        'getGoodsDetail',
        'getBusinessCommentHead',
        'getBusinessCommentList',
        'getGoodsCommentHead',
        'getGoodsCommentList',
        'getAddressListByKeywords',
        'getBrandList'
    ];

    protected function initialize()
    {
        parent::initialize();
        $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $data = $this->request;
        if (in_array($data->routeInfo()['rule'], $this->noRule)) {
            if ($authorization) {
                $openid = $authorization;
                $user = Db::name('member')->where('openid', '=', $openid)
                    ->field('id,openid,nickname,avatarUrl,mobile,status,order_num,save_money,reduction,level,experience,fraction')->find();
                if (empty($user)) {
                    responseJson(-100, '登录信息有误');
                }
                $this->memberInfo = $user;
                if ($user['status'] == 0) {
                    msg(-200, '用户已冻结', $user);
                }
                if (!strpos($user['avatarUrl'], 'ttp')) {
                    $user['avatarUrl'] = config('wechat.url') . $user['avatarUrl'];
                }
                $this->openid = $openid;
                $this->memberInfo = $user;
                $this->memberId = $user['id'];

                $business = Db::name('business')->where([
                    'member_id' => $this->memberId,
                    'is_del' => 0
                ])->find();
                $employ = Db::name('employ')->where([
                    'is_del' => 0,
                    'member_id' => $this->memberId,
                ])->find();
                $this->role = 0;

                if ($employ) {
                    $this->role = 2;
                }
                //todo 商家的等级优先于店员
                if ($business) {
                    $this->role = 1;
                }
            }
        } else {
            if (empty($authorization)) {
                responseJson(-100, '请先登录');
            }
            $openid = $authorization;
            $user = Db::name('member')->where('openid', '=', $openid)
                ->field('id,openid,nickname,avatarUrl,mobile,status,order_num,save_money,reduction,level,experience,fraction')->find();
            if (empty($user)) {
                responseJson(-100, '登录信息有误');
            }
            if ($user['status'] == 0) {
                msg(-200, '用户已冻结', $user);
            }
            if (!strpos($user['avatarUrl'], 'ttp')) {
                $user['avatarUrl'] = config('wechat.url') . $user['avatarUrl'];
            }
            $this->openid = $openid;
            $this->memberInfo = $user;
            $this->memberId = $user['id'];

            $business = Db::name('business')->where([
                'member_id' => $this->memberId,
                'is_del' => 0
            ])->find();
            $employ = Db::name('employ')->where([
                'is_del' => 0,
                'member_id' => $this->memberId,
            ])->find();
            $this->role = 0;
            if ($business) {
                $this->role = 1;
            }
            if ($employ) {
                $this->role = 2;
            }
        }

    }

    /**
     * 获取用户状态
     */
    public function getUserStatus()
    {
        responseJson(0, '账号正常');
    }

    /**
     * 获取用户信息
     */
    public function GetWxUserInfo()
    {
        msg(0, '查询成功', $this->memberInfo);
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 修改用户信息
     */
    public function getUserinfoUpdate()
    {
        $data = $this->request->param();
        $update_data = array();
        if (isset($data['mobile'])) {
            $update_data['mobile'] = $data['mobile'];
        }
        if (isset($data['nickname'])) {
            $update_data['nickname'] = $data['nickname'];
        }
        if (isset($data['avatarUrl'])) {
            $update_data['avatarUrl'] = $data['avatarUrl'];
        }
        $stmt = Db::name('member')
            ->where('openid', $this->openid)
            ->update($update_data);
        if ($stmt) {
            msg(0, "修改成功", []);
        } else {
            msg(0, "修改成功", []);
        }
    }

    /**
     * 获取经营分类
     * @throws \think\exception\DbException
     */
    public function getOperateCateList()
    {
        $where[] = ['status', '=', 1];
        $where[] = ['is_del', '=', 0];
        $data_list = Db::name('operate_cate')->where($where)->order('sort desc')->select();
        msg(0, '查询完成', $data_list);
    }

    /**
     * 获取经营形式
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOperateTypeList()
    {
        $where[] = ['status', '=', 1];
        $where[] = ['is_del', '=', 0];
        $data_list = Db::name('operate_type')->where($where)->order('sort desc')->select();
        msg(0, '查询完成', $data_list);
    }

    /**
     * 获取品牌
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBrandList()
    {
        $where[] = ['status', '=', 1];
        $where[] = ['is_del', '=', 0];
        $data_list = Db::name('brand')->where($where)->order('sort desc')->select();
        msg(0, '查询完成', $data_list);
    }

    /**
     * 获取惊喜袋的
     */
    public function getGoodsLabs()
    {
        $where[] = ['status', '=', 1];
        $where[] = ['is_del', '=', 0];
        $data_list = Db::name('goods_lab')->where($where)->order('sort desc')->select();
        msg(0, '查询完成', $data_list);
    }


    //==============================

    /**
     * 获取成为商家审核状态
     */
    public function getBusinessStatus()
    {
        $data = Db::name('business')->where(['member_id' => $this->memberId,'is_del'=>0])->find();
        if ($data) {
            if (!strpos($data['food_business_license'], 'ttp')) {
                $data['food_business_license'] = config('wechat.url') . $data['food_business_license'];
            }
            if (!strpos($data['business_license'], 'ttp')) {
                $data['business_license'] = config('wechat.url') . $data['business_license'];
            }
            if ($data['status'] == 1) {
                //返回数据
                msg(0, '申请已通过', $data);
            }
            if ($data['status'] == 3) {
                //返回数据
                msg(-3, '审核不通过', $data);
            }
            if ($data['status'] == 2) {
                //返回数据
                msg(-2, '账户冻结,请联系管理员', $data);
            }

            msg(1, '你已申请，等待审核', '');
        }
        msg(-1, '未申请', '');
    }

    /**
     * 申请成为商家
     */
    public function addBusiness()
    {
        $business_data = Db::name('business')->where('is_del', 0)->where(['member_id' => $this->memberId])->find();
        if ($business_data && $business_data['status'] != 3) {    //存在且不是审核失败
            msg(-1, '您已申请,请勿重复提交', '');
        }
        $data = $this->request->param();
        $result = $this->validate($data, 'Business.insert');
        if (true !== $result) {
            msg(-1, $result, '');
        }
        $create_time = time();
        $insert_data = array(
            'member_id' => $this->memberId,
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'business_name' => $data['business_name'],
            'name' => $data['name'],
            'phone' => $data['phone'],
            'food_business_license' => $data['food_business_license'],//食品经营许可
            'business_license' => $data['business_license'],//营业执照
            'amount' => 0.00,
            'create_time' => $create_time,
        );
        if ($data['remark']) {
            $insert_data['remark'] = $data['remark'];
        }
        $address = getLWByAddress($data['province'] . $data['city'] . $data['area'] . $data['address']);
        $address = json_decode($address, true);
        if ($address['code'] == 0) {
            $insert_data['longitude'] = $address['data'][0];
            $insert_data['latitude'] = $address['data'][1];
        } else {
            msg(-1, '输入正确位置', '');
        }
        Db::startTrans();
        try {
            if ($business_data && $business_data['status'] == 3) {
                unset($insert_data['member_id']);
                $insert_data['status'] = 0;
                $business_id = Db::name('business')
                    ->where('is_del','=',0)
                    ->where('member_id', $this->memberId)
                    ->update($insert_data);
            } else {
                $business_id = Db::name('business')
                    ->insertGetId($insert_data);
            }
            Db::commit();
            msg(0, '查询成功', $business_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //申请成为员工
    public function addEmploy()
    {
        $is_employ = Db::name('employ')
            ->where('member_id', '=', $this->memberId)
            ->where('is_del', '=', 0)
            ->find();
        if ($is_employ) {
            msg(-1, '已注册成为员工', '');
        }
        $business_info = Db::name('business')->where([
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->find();
        if ($business_info) {
            msg(-1, '当前为商家,不可成为员工', '');
        }
        $data = $this->request->param();
        $insert_data = array(
            'business_id' => $data['business_id'],
            'member_id' => $this->memberId,
            'name' => $data['name'],
            'phone' => $data['phone'],
            'create_time' => time()
        );
        Db::startTrans();
        try {
            $result_id = Db::name('employ')->insertGetId($insert_data);
            Db::commit();
            msg(0, '查询成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断是否新人可领取优惠券
    public function isXinPeople()
    {
        //新人优惠券 为id 1
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['coupon_id', '=', 1];
        $where[] = ['is_del', '=', 0];
        $member_coupons = Db::name('member_coupons')->where($where)->find();
        $coupon_info = Db::name('coupons')->find(1);
        if ($member_coupons) {
            msg(-1, '', '');
        }
        msg(0, '查询成功', $coupon_info);
    }

    //获取新人优惠券
    public function getXinCoupons()
    {
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['coupon_id', '=', 1];
        $where[] = ['is_del', '=', 0];
        $member_coupons = Db::name('member_coupons')->where($where)->find();
        if ($member_coupons) {
            msg(-1, '已领取新人优惠券', '');
        }
        $coupon_info = Db::name('coupons')->find(1);
        if (!$coupon_info) {
            msg(-1, '新人优惠券不存在', '');
        }
        Db::startTrans();
        try {
            $result_id = getCoupons($this->memberId, $coupon_info);
            Db::commit();
            msg(0, '查询成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //收藏 商家
    public function collectBusiness()
    {
        $data = $this->request->param();
        $insert_data = array(
            'member_id' => $this->memberId,
            'type' => 2,
            'object_id' => $data['business_id'],
        );
        Db::startTrans();
        try {
            $collect_info = Db::name('collect')->where($insert_data)->find();
            if ($collect_info) {
                msg(-1, '你已收藏此商家', '');
            }
            $insert_data['create_time'] = time();
            $result_id = Db::name('collect')->insertGetId($insert_data);
            Db::commit();
            msg(0, '查询成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //取消 商家 cancel
    public function cancelBusiness()
    {
        $data = $this->request->param();
        $where = array(
            'member_id' => $this->memberId,
            'type' => 2,
            'object_id' => $data['business_id'],
        );
        Db::name('collect')->where($where)->delete();
        msg(0, '查询成功', '');
    }


    //首页 获取
    public function getBusinessList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 1000);
        //当前市   city
        //获取当前 经纬度  longitude   latitude
        //显示范围 单位米  range
        //商家品牌 数组 [2,3,4,5] brand_ids[]
        //食品袋分类 cate_id


        //搜索字段 食品袋标签 商家名称 search_key
        //现在可取      is_get 1
        //现在可买      is_buy 1

        //评分最高      is_score
        //价格最低      is_low


        $business_where[] = ['is_del', '=', 0];
        $business_where[] = ['city', '=', $data['city']];
        $business_where[] = ['status', '=', 1];
//        $business_where[] = ['operation_status', '=', 1];

        $goods_where[] = ['is_del', '=', 0];
        $goods_where[] = ['status', '=', 1];

        if ($data['brand_ids']) {
            $business_where[] = ['brand', 'in', $data['brand_ids']];
        }
        if ($data['is_score']) {
            $data_list = Db::name('business')
                ->where($business_where)
                ->order('evaluate desc')
                ->page($page, $length)
                ->select();
        } else {
            $data_list = Db::name('business')
                ->where($business_where)
                ->page($page, $length)
                ->select();
        }
        foreach ($data_list as $k => $v) {
            $data_list[$k]['distance'] = distanceHaversine($data['latitude'], $data['longitude'], $v['latitude'], $v['longitude']);
            $data_list[$k]['distance'] = floor($data_list[$k]['distance'] * 1000);
            $data_list[$k]['open'] = false;
            //现在可取      is_get 1
            //现在可买      is_buy 1
            $now_time = date('H:i', time());
            if ($data['is_get']) {   //当前是否可取
                $goods_where[] = ['qu_time_start', '<', $now_time];
                $goods_where[] = ['qu_time_end', '>', $now_time];
            }
            if ($data['is_buy']) {   //当前是否可买
                $goods_where[] = ['purchase_time_start', '<', $now_time];
                $goods_where[] = ['purchase_time_end', '>', $now_time];
            }
            //价格最低      is_low
            if ($data['is_low']) {
                $goods_list = Db::name('goods')
                    ->where('business_id', $v['id'])
                    ->where($goods_where)
                    ->order('price')
                    ->select();
            } else {
                $goods_list = Db::name('goods')
                    ->where('business_id', $v['id'])
                    ->where($goods_where)
                    ->select();
            }

            //商品分类cate_id
            foreach ($goods_list as $k2 => $v2) {
                if ($data['cate_id']) {
                    $cate_array = explode(',', $v2['cate_id']);
                    if (!in_array($data['cate_id'], $cate_array)) {
                        unset($goods_list[$k2]);
                    }
                }
            }
            //todo 不传为空 设置默认的range范围
            if (!$data['range']) {
                $data['range'] = 50000;
            }
            //商家距离
            if (($data_list[$k]['distance'] > $data['range']) || (empty($goods_list))) {
                unset($data_list[$k]);
                continue;
            }
            //是否收藏商家
            $collect_where = array(
                'type' => 2,
                'object_id' => $v['id'],
                'member_id' => $this->memberId,
            );
            $collect = Db::name('collect')->where($collect_where)->find();
            $data_list[$k]['collect'] = 0;
            if ($collect) {
                $data_list[$k]['collect'] = 1;
            }
            $data_list[$k]['goods'] = $goods_list;
        }
        if ($data['search_key']) {
            foreach ($data_list as $k => $v) {
                $a = false;
                $b = false;
                if (strpos($v['business_name'], $data['search_key']) !== false) {
                    $a = true;
                }
                foreach ($v['goods'] as $k2 => $v2) {
                    if (strpos($v2['name'], $data['search_key']) !== false || strpos($v2['labels'], $data['search_key']) !== false) {
                        $b = true;
                    } else {
                        unset($v2[$k2]);
                    }
                }
                if (!$a && !$b) {
                    unset($data_list[$k]);
                }
            }
        }

        if (!$data['is_score']) {
            usort($data_list, function ($a, $b) {
                return $a['distance'] - $b['distance'];
            });
        }
        usort($data_list, function ($a, $b) {
            return $b['operation_status'] - $a['operation_status'];
        });
        msg(0, '查询成功', $data_list, count($data_list));
    }


    //用户端获取商家详情
    public function getBusinessDetail()
    {
        $data = $this->request->param();
        //business_id
        //获取当前 经纬度  longitude   latitude
        $business = Db::name('business')
            ->where('id', $data['business_id'])
            ->find();
        if (!$business) {
            msg(-1, '商家不存在', '');
        }
        $comment = Db::name('comment')
            ->where([
                'business_id' => $data['business_id'],
                'reply_id' => 0,
                'status' => 1,
                'is_del' => 0
            ])
            ->count();

        $operate_type = Db::name('operate_type')->find($business['operate_type']);
        $business['operate_type_name'] = $operate_type['name'];
        $operate_cate_id = explode(',', $business['operate_cate']);
        $operate_cate = Db::name('operate_cate')->where('id', 'in', $operate_cate_id)->column('name');
        $operate_cate = implode('/', $operate_cate);
        $business['operate_cate_name'] = $operate_cate;


        $business['comment_count'] = $comment;
        $business['distance'] = distanceHaversine($data['latitude'], $data['longitude'], $business['latitude'], $business['longitude']);
        $business['distance'] = floor($business['distance'] * 1000);
        msg(0, '查询成功', $business);
    }

    //获取商家商品列表
    public function getGoodsList()
    {
        $data = $this->request->param();
        //  'business_id'=>$data['business_id'],
        $data_list = Db::name('goods')
            ->where([
                'business_id' => $data['business_id'],
                'is_del' => 0,
                'status' => 1
            ])
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //获取商品详情
    public function getGoodsDetail()
    {
        $data = $this->request->param();
        $goods_info = Db::name('goods')
            ->find($data['goods_id']);
        $business_info = Db::name('business')->find($goods_info['business_id']);
        $goods_info['address'] = $business_info['address'];

        //是否收藏商品
        $collect_where = array(
            'type' => 1,
            'object_id' => $data['goods_id'],
            'member_id' => $this->memberId,
        );
        $collect = Db::name('collect')->where($collect_where)->find();
        $goods_info['collect'] = 0;
        if ($collect) {
            $goods_info['collect'] = 1;
        }
        $now_time = date('H:i', time());
        if ($goods_info['inventory'] > 0 && $goods_info['purchase_time_start'] <= $now_time && $goods_info['purchase_time_end'] >= $now_time && $business_info['operation_status'] == 1) {
            $goods_info['is_buy'] = 1;
        } else {
            $goods_info['is_buy'] = 0;
        }
        if ($goods_info['is_buy'] == 0) {
            $presale = Db::name('presale')->where([
                'member_id' => $this->memberId,
                'goods_id' => $goods_info['id'],
                'is_del' => 0
            ])->find();
            if ($presale) {
                $goods_info['is_buy'] = 2;
            }
        }
        msg(0, '查询成功', $goods_info);
    }

    //获取商品评论

    //收藏惊喜袋 collect
    public function collectGoods()
    {
        $data = $this->request->param();
        $insert_data = array(
            'member_id' => $this->memberId,
            'type' => 1,
            'object_id' => $data['goods_id'],
        );
        Db::startTrans();
        try {
            $collect_info = Db::name('collect')->where($insert_data)->find();
            if ($collect_info) {
                msg(-1, '你已收藏此商品', '');
            }
            $insert_data['create_time'] = time();
            $result_id = Db::name('collect')->insertGetId($insert_data);
            Db::commit();
            msg(0, '查询成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //取消惊喜袋 cancel
    public function cancelGoods()
    {
        $data = $this->request->param();
        $where = array(
            'member_id' => $this->memberId,
            'type' => 1,
            'object_id' => $data['goods_id'],
        );
        Db::name('collect')->where($where)->delete();
        msg(0, '查询成功', '');
    }

    //获取推荐关键词
    public function getRecommendList()
    {
        $data_list = Db::name('recommend')
            ->where([
                'status' => 1,
                'is_del' => 0
            ])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //通过关键字获取相关地址
    public function getAddressListByKeywords()
    {
        $data = $this->request->param();
        //当前维度 经度 搜索关键字 页数 所在市
        $page = input('page/d', 1);
        $data_list = getAddressListByKeywords($data['city'], $data['latitude'], $data['longitude'], $data['keyword'], $page);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            msg(0, '查询成功', $data_list['data']);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }


    //通过商品获取用户优惠券 显示是否可用
    public function getMemberCoupons()
    {
        $data = $this->request->param();
        $goods_info = Db::name('goods')
            ->where('id', '=', $data['goods_id'])
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        $where = array(
            'member_id' => $this->memberId,
            'status' => 1,
            'is_del' => 0
        );
        $time = time();
        $where2[] = ['start_time', '<=', $time];
        $where2[] = ['end_time', '>=', $time];
        $data_list = Db::name('member_coupons')
            ->where($where)
            ->where($where2)
            ->order('create_time desc')
            ->select();
        foreach ($data_list as $k => $v) {
            if ($v['min_amount'] <= $goods_info['price']) {
                $data_list[$k]['is_able'] = 1;
            } else {
                $data_list[$k]['is_able'] = 0;
            }
        }
        msg(0, '查询成功', $data_list);
    }

    //创建订单
    public function createOrder()
    {
        $data = $this->request->param();
        //判断库存 是否可买
        $where = array(
            'id' => $data['goods_id'],
            'is_del' => 0,
            'status' => 1
        );
        $goods_info = Db::name('goods')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        if ($goods_info['inventory'] <= 0) {
            msg(-1, '商品库存不足', '');
        }
        $buy_time = date('H:i', time());
        if (!($goods_info['purchase_time_start'] < $buy_time && $buy_time < $goods_info['purchase_time_end'])) {
            msg(-1, '当前不可购买', '');
        }
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'business_id' => $goods_info['business_id'],
            'goods_id' => $data['goods_id'],
            'status' => 1,//1待支付 2待取货 3待评价 4已退款 5已失效
            'pay_status' => 0,
            'create_time' => time(),
            'price' => $goods_info['price'],
            'remark' => $data['remark'],
            'mc_id' => 0, //会员优惠券id
            'coupon_money' => 0,  //优惠金额
            'pay_money' => $goods_info['price'],//实际支付金额
            'write_status' => 0,
            'is_tui' => 0,
            'is_del' => 0,
            'qu_time_start' => strtotime($goods_info['qu_time_start']),
            'qu_time_end' => strtotime($goods_info['qu_time_end']),
            'carbon_emissions' => $goods_info['co2'],
            'mobile' => $data['phone']
        );
        $business_info = Db::name('business')->find($goods_info['business_id']);
        if ($business_info['operation_status'] == 0) {
            msg(-1, '商家已打样', '');
        }
        //使用优惠券
        if (isset($data['mc_id']) && $data['mc_id']) {
            $coupons_where = array(
                'member_id' => $this->memberId,
                'id' => $data['mc_id'],
                'status' => 1,
                'is_del' => 0,
            );
            $member_coupons = Db::name('member_coupons')
                ->where($coupons_where)
                ->find();
            if (!$member_coupons) {
                msg(-1, '优惠券不存在', '');
            }
            if ($goods_info['price'] < $member_coupons['min_amount']) {
                msg(-1, '优惠券不可用', '');
            }
            $insert_data['mc_id'] = $data['mc_id'];
            $insert_data['coupon_money'] = $member_coupons['value'];
            $insert_data['pay_money'] = number_format($insert_data['price'] - $member_coupons['value'], 2);
        }

        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['mc_id']) && $data['mc_id']) {
                //优惠券状态修改
                Db::name('member_coupons')->update(
                    [
                        'id' => $data['mc_id'],
                        'status' => 2,
                        'used_time' => time(),
                        'order_id' => $order_id
                    ]
                );
            }
            $insert_data['id'] = (int)$order_id;
            Db::commit();
            msg(0, '查询完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //删除订单
    public function delOrder()
    {
        $data = $this->request->param();
        //todo 订单不是自己的不可删除
        Db::startTrans();
        try {
            Db::name('order')->update([
                'id' => $data['id'],
                'is_del' => 1
            ]);
            Db::commit();
            msg(0, '查询完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //订单支付发起
    public function payGoodsOrder()
    {
        //库存为0不能下订单
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $goods_info = Db::name('goods')->find($order_data['goods_id']);
        if ($goods_info['inventory'] <= 0) {
            msg(-1, '商品库存不足', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '食品袋购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //订单回调
    public function payOrderBack()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        $res = $app->order->queryByOutTradeNumber($order_no);
        if ($res['trade_state'] == "SUCCESS") {
            $this->orderPaySuccess($order_data);
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    //获取订单详情
    public function orderDetail()
    {
        //生成核销码编号 核销二维码
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $order_data = Db::name('order')
            ->where('id', '=', $order_id)
            ->find();
        Db::startTrans();
        try {
            if (!$order_data) {
                msg(-1, '订单有误', '');
            }
            if (!$data['longitude'] || !$data['latitude']) {
                msg(-1, '请传递坐标', '');
            }
            if ($order_data['pay_status'] == 1 && (!$order_data['write_code'])) {
                $write_code_digits = rand(1000, 9999);
                //todo 上线后增加页面路径
                $qr_code = qrcode('order_id', $order_id, 'pages1/order/OrderDetails/OrderDetails');
                $update_order = array(
                    'id' => $order_id,
                    'write_code' => $qr_code,
                    'write_code_digits' => $write_code_digits
                );
                Db::name('order')->update($update_order);
                $order_data['write_code'] = $qr_code;
                $order_data['write_code_digits'] = $write_code_digits;
            }
            $order_data['expire_time'] = $order_data['create_time'] + (config('site.tui_time') * 60);
            $order_data['create_time2'] = $order_data['create_time'];
            $order_data['create_time'] = date('Y-m-d H:i:s', $order_data['create_time']);
            if ($order_data['pay_time']) {
                $order_data['pay_time'] = date('Y-m-d H:i:s', $order_data['pay_time']);
            }
            if ($order_data['tui_time']) {
                $order_data['tui_time'] = date('Y-m-d H:i:s', $order_data['tui_time']);
            }
            //获取商家信息
            $business_info = Db::name('business')->find($order_data['business_id']);
            //商家距离 	116.936668,36.674531
            $business_info['distance'] = distanceHaversine($data['latitude'], $data['longitude'], $business_info['latitude'], $business_info['longitude']);
            $business_info['distance'] = floor($business_info['distance'] * 1000);

            //获取商品信息
            $goods_info = Db::name('goods')->find($order_data['goods_id']);
            $result['order'] = $order_data;
            $result['business'] = $business_info;
            $result['goods'] = $goods_info;
            $result['comment']=getOrderComment($order_id);
            Db::commit();
            msg(0, '', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //订单列表
    public function getOrderList()
    {
        //todo 下单时间+15分钟时间戳 进行倒计时
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['is_del', '=', 0];
        if (isset($data['status']) && $data['status']) {
            $where[] = ['status', '=', $data['status']];
        }
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);

        $order_list = Db::name('order')
            ->where($where)
            ->order('create_time desc')
            ->paginate(
                $length, false, [
                    'page' => $page
                ]
            )->each(function ($item) use ($app) {
                if ($item['status'] == 1) {
                    $res = $app->order->queryByOutTradeNumber($item['order_no']);
                    if ($res['trade_state'] == "SUCCESS") {
                        $this->orderPaySuccess($item);
                    }
                }
                //获取商家信息
                $business_info = Db::name('business')->find($item['business_id']);
                //获取商品信息
                $goods_info = Db::name('goods')->find($item['goods_id']);
                $item['business'] = $business_info;
                $item['goods'] = $goods_info;
                $item['expire_time'] = $item['create_time'] + 60 * 15;
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['tui_time']) {
                    $item['tui_time'] = date('Y-m-d H:i:s', $item['tui_time']);
                }
                //评价信息
                $item['comment']=getOrderComment($item['id']);
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    //获取退款原因
    public function getRefundList()
    {
        $data_list = Db::name('refund_reason')->where([
            'is_del' => 0,
            'status' => 1
        ])->order('sort desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['is_select'] = 0;
        }
        msg(0, '查询成功', $data_list);
    }


    //取消订单
    public function cancelOrder()
    {
        $data = $this->request->param();
        //修改订单状态
        //修改优惠券
        Db::startTrans();
        try {
            $order_info = Db::name('order')->where('id', '=', $data['id'])->find();
            if (!$order_info) {
                msg(-1, '订单不存在', '');
            }
            if ($order_info['status'] != 1) {
                msg(-1, '订单状态不是待支付', '');
            }
            $order_data = array(
                'id' => $data['id'],
                'status' => 7,
            );
            Db::name('order')->update($order_data);
            if ($order_info['mc_id']) {
                $mc_update_data = array(
                    'id' => $order_info['mc_id'],
                    'status' => 1,
                    'used_time' => '',
                );
                Db::name('member_coupons')->update($mc_update_data);
            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取收藏商家列表
    public function getCollectBusinessList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 100);
        //range 范围距离 单位米
        //brand_ids[] 商家品牌  品牌id 不传为空
        //is_get    现在可取 0不选 1选
        //is_buy    现在可买  0不选 1选
        $where[] = ['c.type', '=', 2];
        $where[] = ['c.member_id', '=', $this->memberId];

        if ($data['brand_ids']) {
            $where[] = ['b.brand', 'in', $data['brand_ids']];
        }
        $business_list = Db::name('collect')
            ->alias('c')
            ->rightJoin('business b', 'c.object_id=b.id')
            ->field('c.*,b.business_name,b.id as business_id,b.logo_url,b.evaluate,b.longitude,b.latitude,b.brand,b.operation_status')
            ->order('c.create_time desc')
            ->where($where)
            ->page($page, $length)
            ->select();
        foreach ($business_list as $k => $v) {
            $business_list[$k]['is_select'] = false;
            $business_list[$k]['is_collect'] = 1;
            $business_list[$k]['value'] = (string)$v['business_id'];
            $business_list[$k]['distance'] = distanceHaversine($data['latitude'], $data['longitude'], $v['latitude'], $v['longitude']);
            $business_list[$k]['distance'] = floor($business_list[$k]['distance'] * 1000);
            if ($data['range']) {
                if (($business_list[$k]['distance'] > $data['range'])) {
                    unset($business_list[$k]);
                    continue;
                }
            }
            $business_list[$k]['select'] = false;
            $now_time = date('H:i', time());
            $goods_where = array();
            if ($data['is_get']) {   //当前是否可取
                $goods_where[] = ['qu_time_start', '<', $now_time];
                $goods_where[] = ['qu_time_end', '>', $now_time];
            }
            if ($data['is_buy']) {   //当前是否可买
                $goods_where[] = ['purchase_time_start', '<', $now_time];
                $goods_where[] = ['purchase_time_end', '>', $now_time];
            }
            $goods_list = Db::name('goods')
                ->where([
                    ['business_id', '=', $v['business_id']],
                    ['is_del', '=', 0],
                    ['status', '=', 1],
                ])
                ->where($goods_where)
                ->select();
            $business_list[$k]['goods'] = $goods_list;
            if (empty($goods_list)) {
                unset($business_list[$k]);
                continue;
            }
        }
        msg(0, '查询成功', $business_list, count($business_list));
    }

    //获取收藏商品列表
    public function getCollectGoodsList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 100);
        $where[] = ['c.type', '=', 1];
        $where[] = ['c.member_id', '=', $this->memberId];
        $where[] = ['g.status', 'in', [1, 4]];
        $where[] = ['g.is_del', '=', 0];
        if ($data['brand_ids']) {
            $where[] = ['b.brand', 'in', $data['brand_ids']];
        }
        $now_time = date('H:i', time());
        if ($data['is_get']) {
            $where[] = ['g.qu_time_start', '<', $now_time];
            $where[] = ['g.qu_time_end', '>', $now_time];
        }
        if ($data['is_buy']) {   //当前是否可买
            $where[] = ['g.purchase_time_start', '<', $now_time];
            $where[] = ['g.purchase_time_end', '>', $now_time];
        }
        $goods_list = Db::name('collect')
            ->alias('c')
            ->rightJoin('goods g', 'c.object_id=g.id')
            ->rightJoin('business b', 'b.id=g.business_id')
            ->field('c.id as collect_id,g.*,b.business_name,b.id as business_id,b.longitude,b.latitude,b.brand')
            ->where($where)
            ->order('c.create_time desc')
            ->paginate(
                $length, false, [
                    'page' => $page
                ]
            )->each(function ($item) use ($data) {
                $item['distance'] = distanceHaversine($data['latitude'], $data['longitude'], $item['latitude'], $item['longitude']);
                $item['distance'] = floor($item['distance'] * 1000);
                $item['value'] = (string)$item['id'];
                if ($data['range']) {
                    if (($item['distance'] > $data['range'])) {
                        unset($item);
                    }
                }
                $item['select'] = false;
                return $item;
            });
        msg(0, '查询成功', $goods_list, $goods_list->total());
    }

    //批量取消收藏商品
    public function cancelCollectGoodsByIds()
    {
        $data = $this->request->param();
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['type', '=', 1];
        $where[] = ['object_id', 'in', $data['goods_ids']];
        Db::name('collect')->where($where)->delete();
        msg(0, '查询成功', '');

    }

    //批量取消收藏商家
    public function cancelCollectBusinessByIds()
    {
        $data = $this->request->param();
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['type', '=', 2];
        $where[] = ['object_id', 'in', $data['business_ids']];
        Db::name('collect')->where($where)->delete();
        msg(0, '查询成功', '');
    }


    //用户评价  todo 对接第三方接口评论 图片
    public function createComment()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')
            ->where([
                'id' => $data['order_id'],
                'member_id' => $this->memberId,
            ])->find();
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
        if ($order_info['status'] != 3) {
            msg(-1, '订单已评论', '');
        }
        $insert_data = array(
            'member_id' => $this->memberId,
            'order_id' => $data['order_id'],
            'goods_id' => $order_info['goods_id'],
            'business_id' => $order_info['business_id'],
            'content' => $data['content'],
            'reply_id' => 0,
            //'label' => '味道好,分量大',
            'score' => $data['score'],
            'anonymous' => $data['anonymous'],
            'create_time' => time(),
        );
        if ($data['label_ids']) {
            $comment_labs = Db::name('comment_label')
                ->where([
                    ['id', 'in', $data['label_ids']]
                ])->column('name');
            if ($comment_labs) {
                $insert_data['label'] = implode(',', $comment_labs);
            }
        }
        Db::startTrans();
        try {
            $comment_id = Db::name('comment')->insertGetId($insert_data);
            //更新订单信息
            Db::name('order')->update(
                [
                    'id' => $data['order_id'],
                    'status' => 6,
                    'evaluate' => $data['score']
                ]
            );
            //更新商品评分
            updateGoodsEvaluate($order_info['goods_id']);
            //更新商家评分
            updateBusinessEvaluate($order_info['business_id']);
            if (isset($data['comment_imgs']) && $data['comment_imgs']) {
                foreach ($data['comment_imgs'] as $k => $v) {
                    Db::name('comment_img')->insertGetId(
                        [
                            'comment_id' => $comment_id,
                            'img_url' => $v,
                            'sort' => $k + 1
                        ]
                    );
                }
            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //回复评论
    public function replyComment()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $comment = Db::name('comment')
                ->where([
                    'id' => $data['comment_id'],
                    'is_del' => 0,
                ])
                ->find();
            if (!$comment) {
                msg(-1, '评论不存在', '');
            }
            $insert_data = array(
                'member_id' => $this->memberId,
                'content' => $data['content'],
                'create_time' => time(),
                'reply_id' => $data['comment_id']
            );
            $comment_id = Db::name('comment')->insertGetId($insert_data);
            //todo 插入消息通知
            sendMessage($comment['member_id'], $this->memberInfo['nickname'] . '评论了你的信息', 4, 2, $this->memberId);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取商家评论顶部信息
    public function getBusinessCommentHead()
    {
        $data = $this->request->param();

//        $order_count = Db::name('order')->where([
//            'business_id' => $data['business_id'],
//            'status' => 6,
//            'is_tui' => 0
//        ])->count();
//        $order_count_hao = Db::name('order')->where([
//            'business_id' => $data['business_id'],
//            'status' => 6,
//            'is_tui' => 0,
//        ])->where('evaluate', '>=', 4)->count();

        $order_count = Db::name('comment')
            ->where([
                'business_id' => $data['business_id'],
                'reply_id' => 0,
                'status' => 1,
                'is_del' => 0,
            ])->count();

        $order_count_hao = Db::name('comment')
            ->where([
                'business_id' => $data['business_id'],
                'reply_id' => 0,
                'status' => 1,
                'is_del' => 0,
            ])->where('score', '>=', 4)->count();


        $business_info = Db::name('business')
            ->find($data['business_id']);
        $return_data['business_evaluate'] = $business_info['evaluate'];
        $return_data['comment_count'] = $order_count;

        if ($order_count == 0) {
            $return_data['haoRatio'] = 100;
        } else {
            $return_data['haoRatio'] = round(($order_count_hao / $order_count) * 100);
        }
        $comment = Db::name('comment')->where([
                'business_id' => $data['business_id'],
                'is_del' => 0,
                'status' => 1,
                'reply_id' => 0
            ]
        )->where('label', '<>', null)->column('label');
        $comment_labs = array();
        foreach ($comment as $k => $v) {
            $comment2 = explode(',', $v);
            foreach ($comment2 as $k2 => $v2) {
                $comment_labs[] = $v2;
            }
        }
        $comment_labs = array_count_values($comment_labs);
        $return_data['comment_labs'] = $comment_labs;
        //获取商家评分 获取商家评论数量 获取商家好评率
        //获取各类标签
        msg(0, '查询成功', $return_data);
    }

    public function getBusinessCommentList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 100);
        $comment_list = Db::name('comment')
            ->where([
                'business_id' => $data['business_id'],
                'reply_id' => 0,
                'status' => 1,
                'is_del' => 0,
            ])->order('create_time desc')
            ->paginate(
                $length, false, [
                    'page' => $page
                ]
            )->each(function ($item) {
                //判断是否匿名用户
                if ($item['anonymous']) {
                    $item['user_name'] = '匿名用户';
                    $item['user_avatar_url'] = config('site.web_default_avatar');
                } else {
                    $member_info = Db::name('member')->find($item['member_id']);
                    $item['user_name'] = $member_info['nickname'];
                    $item['user_avatar_url'] = $member_info['avatarUrl'];
                }
                //显示商品
                $goods_info = Db::name('goods')->find($item['goods_id']);
//                if ($goods_info) {
//                    $item['goods_name'] = $goods_info['name'];
//                } else {
//                    $item['goods_name'] = '其他商品';
//                }
                $item['goods_info'] = $goods_info;
                //评论图片
                $item['img'] = Db::name('comment_img')
                    ->where('comment_id', '=', $item['id'])
                    ->order('sort desc')
                    ->column('img_url');
//                $item['img']=explode(',',$comment_img);

                $item['create_time'] = date('Y-m-d', $item['create_time']);
                $item['reply_count'] = Db::name('comment')
                    ->where('reply_id', $item['id'])
                    ->count();
                return $item;
            });
        msg(0, '查询成功', $comment_list);
    }

    //商品评论顶部
    public function getGoodsCommentHead()
    {
        $data = $this->request->param();
//        $order_count = Db::name('order')->where([
//            'goods_id' => $data['goods_id'],
//            'status' => 6,
//            'is_tui' => 0
//        ])->count();
        $order_count = Db::name('comment')
            ->where([
                'goods_id' => $data['goods_id'],
                'reply_id' => 0,
                'status' => 1,
                'is_del' => 0,
            ])->count();

        $order_count_hao = Db::name('comment')
            ->where([
                'goods_id' => $data['goods_id'],
                'reply_id' => 0,
                'status' => 1,
                'is_del' => 0,
            ])->where('score', '>=', 4)->count();
//        $order_count_hao = Db::name('order')->where([
//            'goods_id' => $data['goods_id'],
//            'status' => 6,
//            'is_tui' => 0,
//        ])->where('evaluate', '>=', 4)->count();

        $goods_info = Db::name('goods')
            ->find($data['goods_id']);
        $return_data['evaluate'] = $goods_info['evaluate'];

        $return_data['comment_count'] = $order_count;
        if ($order_count == 0) {
            $return_data['haoRatio'] = 100;
        } else {
            $return_data['haoRatio'] = round(($order_count_hao / $order_count) * 100);
        }
        $comment = Db::name('comment')->where([
                'goods_id' => $data['goods_id'],
                'is_del' => 0,
                'status' => 1,
                'reply_id' => 0
            ]
        )->where('label', '<>', null)->column('label');
        $comment_labs = array();
        foreach ($comment as $k => $v) {
            $comment2 = explode(',', $v);
            foreach ($comment2 as $k2 => $v2) {
                $comment_labs[] = $v2;
            }
        }
        $comment_labs = array_count_values($comment_labs);
        $return_data['comment_labs'] = $comment_labs;
        msg(0, '查询成功', $return_data);
    }

    //获取商品评论
    public function getGoodsCommentList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 100);
        $comment_list = Db::name('comment')
            ->where([
                'goods_id' => $data['goods_id'],
                'reply_id' => 0,
                'status' => 1,
                'is_del' => 0,
            ])->order('create_time desc')
            ->paginate(
                $length, false, [
                    'page' => $page
                ]
            )->each(function ($item) {
                //判断是否匿名用户
                if ($item['anonymous']) {
                    $item['user_name'] = '匿名用户';
                    //todo config 设置 //{:config('site.web_default_avatar')}
                    $item['user_avatar_url'] = config('site.web_default_avatar');
                } else {
                    $member_info = Db::name('member')->find($item['member_id']);
                    $item['user_name'] = $member_info['nickname'];
                    $item['user_avatar_url'] = $member_info['avatarUrl'];
                }
                //显示商品
                $goods_info = Db::name('goods')->find($item['goods_id']);
//                if ($goods_info) {
//                    $item['goods_name'] = $goods_info['name'];
//                } else {
//                    $item['goods_name'] = '其他商品';
//
//                }
                $item['goods_info'] = $goods_info;
                //评论图片
                $item['img'] = Db::name('comment_img')
                    ->where('comment_id', '=', $item['id'])
                    ->order('sort desc')
                    ->column('img_url');

                $item['create_time'] = date('Y-m-d', $item['create_time']);
                $item['reply_count'] = Db::name('comment')
                    ->where('reply_id', $item['id'])
                    ->count();
                return $item;
            });
        msg(0, '查询成功', $comment_list);
    }

    //评论回复信息
    public function getReply()
    {
        $data = $this->request->param();
        //获取评论id comment_id
        $comment_info = Db::name('comment')
            ->alias('c')
            ->join('member m', 'c.member_id=m.id')
            ->join('goods g', 'c.goods_id=g.id')
            ->field('c.*,g.name,m.nickname,m.avatarUrl')
            ->where([
                'c.id' => $data['comment_id'],
                'c.status' => 1,
                'c.is_del' => 0
            ])->find();
        if (!$comment_info) {
            msg(-1, '评论不存在', '');
        }
        $comment_info['create_time'] = date('Y-m-d', $comment_info['create_time']);
        if ($comment_info['anonymous'] == 1) {
            $comment_info['nickname'] = '匿名用户';
            $comment_info['avatar_url'] = config('site.web_default_avatar');
        }
        $comment_img = Db::name('comment_img')->where([
            'comment_id' => $data['comment_id']
        ])->order('sort')->select();
        $comment_info['comment_img'] = $comment_img;
        //回复数据
        $reply_comment = Db::name('comment')->where([
            'is_del' => 0,
            'reply_id' => $data['comment_id']
        ])->order('create_time desc')->select();
        foreach ($reply_comment as $k => $v) {
            $reply_comment[$k]['create_time'] = date('Y-m-d', $v['create_time']);
            if ($v['reply_role'] == 1) {
                $member_info = Db::name('member')->find($v['member_id']);
                $reply_comment[$k]['user_name'] = $member_info['nickname'];
                $reply_comment[$k]['user_avatar_url'] = $member_info['avatarUrl'];
            } else if ($v['reply_role'] == 2) {
                $business_info = Db::name('business')->find($v['business_id']);
                $reply_comment[$k]['user_name'] = $business_info['business_name'];
                $reply_comment[$k]['user_avatar_url'] = $business_info['logo_url'];
            } else if ($v['reply_role'] == 3) {
                $reply_comment[$k]['user_name'] = '资产标注';
                $reply_comment[$k]['user_avatar_url'] = config('site.web_default_avatar');
            }
        }
        $comment_info['reply_comments'] = $reply_comment;
        msg(0, '查询成功', $comment_info);
    }

    //会员签到
    public function sign()
    {
        //当天是否签到
        $timeRang = getTimestamp(0);
        $sign_time = date('Y-m-d', time());
        $sign_info = Db::name('fraction_record')->where([
            ['member_id', '=', $this->memberId],
            ['sign_time', '=', $sign_time]
        ])->find();
        if ($sign_info) {
            msg(-1, '今日已签到', '');
        }
        Db::startTrans();
        try {
            $fraction_count = config('site.web_sign_in_integral') ? config('site.web_sign_in_integral') : 2;
            $experience_count = config('site.web_sign_in_experience') ? config('site.web_sign_in_experience') : 2;
            addFraction($this->memberId, $fraction_count);
            addExperience($this->memberId, $this->memberInfo, $experience_count);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //通过年月显示每页
    public function signList()
    {
        $data = $this->request->param();
        //获取年 获取月
        $year = $data['year'] ? $data['year'] : date('Y', time());
        $month = $data['month'] ? $data['month'] : date('m', time());
        $fraction_num = config('site.web_sign_in_integral') ? config('site.web_sign_in_integral') : 2;
        $result = array();
        $sign_count = 0;
        $dateList = getMonthTimestamps($year, $month);
        foreach ($dateList as $k => $v) {
            $result[$k]['time'] = $v;
            $result[$k]['date'] = date('Y-m-d', $v);
            $result[$k]['date2'] = date('m.d', $v);
            $result[$k]['date3'] = date('j', $v);
            $result[$k]['weekday'] = date('w', $v);
            switch ($result[$k]['weekday']) {
                case 0:
                    $weekday_cn = "日";
                    break;
                case 1:
                    $weekday_cn = "一";
                    break;
                case 2:
                    $weekday_cn = "二";
                    break;
                case 3:
                    $weekday_cn = "三";
                    break;
                case 4:
                    $weekday_cn = "四";
                    break;
                case 5:
                    $weekday_cn = "五";
                    break;
                case 6:
                    $weekday_cn = "六";
                    break;
            }
            $result[$k]['weekday'] = $weekday_cn;
            $result[$k]['fraction_num'] = $fraction_num;
            $sign_info = Db::name('fraction_record')->where([
                ['member_id', '=', $this->memberId],
                ['sign_time', '=', date('Y-m-d', $v)]
            ])->find();
            if ($sign_info) {
                $result[$k]['is_sign'] = 1;
                $sign_count++;
            } else {
                $now_day = date('Y-m-d', time());
                if ($now_day > $result[$k]['date']) {
                    $result[$k]['is_sign'] = -1;
                } else {
                    $result[$k]['is_sign'] = 0;
                }
            }

        }
        $return['date_list'] = $result;
        $return['sign_count'] = $sign_count;

        msg(0, '查询成功', $return);
    }

    //获取用户等级 经验 徽章
    public function getMemberLevel()
    {
        $return = array();
        //当前会员等级
        $now_level = Db::name('member_level')->where([
            'is_del' => 0,
            'level' => $this->memberInfo['level']
        ])->find();
        $now_level['user_experience'] = $this->memberInfo['experience'];
        $return['now_level'] = $now_level;
        //当前徽章
        $get_list = Db::name('member_level')->where([
            ['is_del', '=', 0],
            ['level', '<=', $this->memberInfo['level']]
        ])->order('level')->select();
        $return['get_list_count'] = count($get_list);
        $return['get_list'] = $get_list;
        //未获取徽章
        $other_list = Db::name('member_level')->where([
            ['is_del', '=', 0],
            ['level', '>', $this->memberInfo['level']]
        ])->order('level')->select();
        $return['other_list'] = $other_list;
        msg(0, '查询成功', $return);
    }

    //我的左上方未读消息
    public function msgCount()
    {
        //获取设置是否未读
        $switch = Db::name('message_switch')->where([
            'member_id' => $this->memberId,
        ])->find();
        $msg_where[] = ['member_id', '=', $this->memberId];
        $msg_where[] = ['is_del', '=', 0];
        $msg_where[] = ['is_du', '=', 0];
        if (!$switch) {
            $du_num = Db::name('message')->where($msg_where)->count();
        } else {
//            if ($switch['is_all'] == 0) {
//                msg(0, '查询成功', 0);
//            }
            if ($switch['is_system'] == 0) {
                $msg_where[] = ['message_cate_id', '<>', 1];
            }
            if ($switch['is_qiandao'] == 0) {
                $msg_where[] = ['message_cate_id', '<>', 2];
            }
            if ($switch['is_coupon'] == 0) {
                $msg_where[] = ['message_cate_id', '<>', 3];
            }
            if ($switch['is_reply'] == 0) {
                $msg_where[] = ['message_cate_id', '<>', 4];
            }
            $du_num = Db::name('message')->where($msg_where)->count();
        }
        msg(0, '查询成功', $du_num);
    }

    //发送消息  todo 评价回复
    public function sendMsg()
    {
        $result = sendMessage($this->memberId, '消息测试1112222', 3, 1, 0);
        if ($result > 1) {
            msg(0, '操作成功', '');
        }
    }

    //获取消息中心 回复评论
    public function getMsgReply()
    {
        $return_msg = Db::name('message_cate')->find(5);
        $replay_msg = Db::name('message')->where([
            'member_id' => $this->memberId,
            'is_du' => 0,
            'message_cate_id' => 4
        ])->order('create_time desc')->find();
        if ($replay_msg) {
            $return_msg['is_du'] = 0;
            $return_msg['content'] = $replay_msg['content'];
        } else {
            $return_msg['is_du'] = 1;
            $return_msg['content'] = '暂无消息';
        }
        msg(0, '查询成功', $return_msg);
    }

    //获取评价回复
    public function getReviewReply()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        //获取个人评价
        $user_comment_ids = Db::name('comment')
            ->where([
                'member_id' => $this->memberId,
                'is_del' => 0,
                'status' => 1
            ])->column('id');
        $return_msg = Db::name('comment')->where([
            ['reply_id', 'in', $user_comment_ids]
        ])->order('create_time desc')->paginate(
            $length, false, [
                'page' => $page
            ]
        )->each(function ($item) {
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            if ($item['reply_role'] == 1) {
                $member_info = Db::name('member')->find($item['member_id']);
                $item['user_name'] = $member_info['nickname'];
                $item['user_avatar_url'] = $member_info['avatarUrl'];
            } else if ($item['reply_role'] == 2) {
                $business_info = Db::name('business')->find($item['business_id']);
                $item['user_name'] = $business_info['business_name'];
                $item['user_avatar_url'] = $business_info['logo_url'];
            } else if ($item['reply_role'] == 3) {
                $item['user_name'] = '资产标注';
                $item['user_avatar_url'] = config('site.web_default_avatar');
            }
            $origin_content = Db::name('comment')->find($item['reply_id']);
            $item['origin_content'] = $origin_content['content'];
            $item['origin_comment_id'] = $origin_content['id'];
            return $item;
        });
        //设置评论消息已读
        Db::name('message')->where([
            ['message_cate_id', '=', 4],
            ['member_id', '=', $this->memberId]
        ])->update([
            'is_du' => 1
        ]);
        msg(0, '查询成功', $return_msg);

    }


    //获取消息列表
    public function getMsgList()
    {
        //显示未读消息数量
        //显示消息列表
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $no_read = Db::name('message')->where([
            'member_id' => $this->memberId,
            'is_du' => 0,
            'is_del' => 0,
        ])->count();
        $data_list = Db::name('message')
            ->alias('m')
            ->field('m.*,mc.name as mc_name,mc.img_url')
            ->join('message_cate mc', 'm.message_cate_id=mc.id')
            ->where([
                ['m.member_id', '=', $this->memberId],
                ['m.is_del', '=', 0],
                ['m.message_cate_id', '<>', 4]
            ])
            ->order('m.create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        //最后为 未读消息数量
        msg(0, '操作成功', $data_list, $no_read);
    }

    //查看消息 消息设置已读
    public function getMsgDetail()
    {
        $data = $this->request->param();
        $msg_detail = Db::name('message')
            ->alias('m')
            ->field('m.*,mc.name as mc_name,mc.img_url')
            ->join('message_cate mc', 'm.message_cate_id=mc.id')
            ->where([
                'm.id' => $data['msg_id'],
                //'m.is_del'=>0,
            ])->find();
        if (!$msg_detail) {
            msg(-1, '消息不存在', '');
        }
        Db::name('message')->update([
            'id' => $data['msg_id'],
            'is_du' => 1
        ]);
        msg(0, '查询成功', $msg_detail);
    }

    //删除消息
    public function delMessage()
    {
        $data = $this->request->param();
        Db::name('message')->update([
            'id' => $data['msg_id'],
            'member_id' => $this->memberId,
            'is_del' => 1
        ]);
        msg(0, '查询成功', '');
    }

    //删除已读消息
    public function delDuMessage()
    {
        Db::name('message')->where([
            'member_id' => $this->memberId,
            'is_du' => 1
        ])->update([
            'is_del' => 1,
        ]);
        msg(0, '查询成功', '');
    }

    //积分明细
    public function fractionHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('fraction_record')->where([
            'member_id' => $this->memberId,
        ])->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //积分商城
    public function getFractionBusiness()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('coupons')->where([
            'cate_id' => 3,
            'is_del' => 0,
            'status' => 1
        ])->order('fraction')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['img_url'] = config('site.web_piao_url');
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //兑换优惠券
    public function fractionConvert()
    {
        $data = $this->request->param();
        $coupon_info = Db::name('coupons')->where([
            'id' => $data['coupons_id'],
        ])->find();
        if (!$coupon_info) {
            msg(-1, '优惠券不存在', '');
        }
        Db::startTrans();
        try {
            //判断积分 使用积分  积分记录
            if ($coupon_info['fraction'] > $this->memberInfo['fraction']) {
                msg(-1, '积分不足', '');
            }
            //兑换优惠券
            $result_id = getCoupons($this->memberId, $coupon_info, 2);
            addFraction($this->memberId, $coupon_info['fraction'], '积分兑换', 2, 2, 1, $data['coupons_id'], $result_id);
            Db::commit();
            msg(0, '查询成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取兑换记录
    public function getChangeRecord()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('fraction_record')
            ->alias('fr')
            ->join('member_coupons mc', 'fr.create_id=mc.id')
            ->field('fr.*,mc.value,mc.min_amount,mc.start_time,mc.end_time,mc.desc,mc.name as coupons_name')
            ->where([
                'fr.member_id' => $this->memberId,
                'fr.type' => 2,
            ])->order('fr.create_time desc')->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
                $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //获取问题反馈类型
    public function getQuestionCate()
    {
        $data_list = Db::name('question_cate')->where([
            'is_del' => 0,
            'status' => 1
        ])->order('sort desc')->select();
        msg(0, '查询成功', $data_list);
    }

    //通过分类获取常见问题
    public function getQuestion()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('question')
            ->where([
                'is_del' => 0,
                'status' => 1,
                'question_cate_id' => $data['cate_id'],
            ])->order('sort desc')
            ->paginate($length, false, ['page' => $page])
            ->each(function ($item) {
                $item['is_open'] = 0;
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //提交反馈问题
    public function createFeedback()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'content' => $data['content'],
                'create_time' => time()
            );
            $comment_id = Db::name('question_feedback')->insertGetId($insert_data);
            if (isset($data['question_feedback_imgs']) && $data['question_feedback_imgs']) {
                foreach ($data['question_feedback_imgs'] as $k => $v) {
                    Db::name('question_feedback_img')->insertGetId(
                        [
                            'mf_id' => $comment_id,
                            'img_url' => $v,
                            'sort' => $k + 1
                        ]
                    );
                }
            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取我的评价
    public function getComment()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('comment')
            ->where([
                'reply_id' => 0,
                'member_id' => $this->memberId,
                'is_del' => 0,
                'status' => 1
            ])->order('create_time desc')
            ->paginate($length, false, ['page' => $page])
            ->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['label'] = explode(',', $item['label']);
                //获取评价图片
                $item['comment_img'] = Db::name('comment_img')->where([
                    'comment_id' => $item['id']
                ])->order('sort desc')->column('img_url');
                //获取购买商品
                $item['goods'] = Db::name('goods')->find($item['goods_id']);
                //商家信息
                $item['business'] = Db::name('business')->find($item['business_id']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //获取个人优惠券
    public function getMemberCouponsList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('member_coupons')->where([
            'status' => 1,
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->order('create_time desc')->paginate($length, false, ['page' => $page])->each(function ($item) {
            //start_time    end_time
            $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
            $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
            $item['back_img_url'] = config('site.web_my_coupons');
            $item['open'] = 0;
            return $item;
        });
        msg(0, '查询成功', $data_list);
    }

    //邀请好友页面
    public function inviteMemberList()
    {
        //获取张数
        $get_coupons_list = Db::name('member_coupons')
            ->alias('mc')
            ->join('member m', 'mc.invite_member_id=m.id')
            ->field('mc.*,m.nickname,m.avatarUrl')
            ->where([
                'mc.member_id' => $this->memberId,
                'mc.is_del' => 0,
                'mc.get_type' => 3
            ])->order('create_time desc')->select();
        foreach ($get_coupons_list as $k => $v) {
            $get_coupons_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $get_coupons_list[$k]['count'] = 1;
        }
        $return['coupons_num'] = count($get_coupons_list);
        $return['member_num'] = count($get_coupons_list);
        $return['invite_list'] = $get_coupons_list;

        msg(0, '查询成功', $return);
        //邀请人数
        //获取列表
    }

    //返回当前地址信息
    public function getAddressByIp()
    {
        $address = getCityByIP();
        msg(0, '查询成功', $address);
    }

    //通过城市返回天气  getWeatherByCity
    public function getWeatherByCity()
    {
        $address = getCityByIP();
        $data = getWeatherByCity($address['city']);
        msg(0, '查询成功', $data);
    }


    //--------------------------公用方法--------------------------------
    //订单支付完成状态更改
    public function orderPaySuccess($order_data)
    {
        //订单状态设置
        //用户优惠券设置设置
        //商品库存设置减少
        $order_update = array(
            'id' => $order_data['id'],
            'status' => 2,
            'pay_time' => time(),
            'pay_status' => 1
        );
        Db::startTrans();
        try {
            Db::name('order')->update($order_update);
            Db::name('goods')->where('id', $order_data['goods_id'])->setDec('inventory');
            if ($order_data['mc_id']) {
                $mc_update = array(
                    'id' => $order_data['mc_id'],
                    'status' => 3,
                );
                Db::name('member_coupons')->update($mc_update);
            }
            Db::commit();
            return 1;
        } catch (\Exception $e) {
            Db::rollback();
            return -1;
        }
    }

    //更新商品评分
    public function updateGoodsEvaluate($goods_id)
    {
        //获取商品订单数量
        $where = array(
            'goods_id' => $goods_id,
            'status' => 6,
            'is_tui' => 0
        );
        $order_num = Db::name('order')
            ->where($where)
            ->count();
        //所有订单评价总和
        $order_evaluate_sum = Db::name('order')
            ->where($where)
            ->sum('evaluate');
        $goods_evaluate = sprintf("%.1f", $order_evaluate_sum / $order_num);
        Db::name('goods')->update(
            [
                'id' => $goods_id,
                'evaluate' => $goods_evaluate
            ]
        );
    }

    //更新商家评分
    public function updateBusinessEvaluate($business_id)
    {
        //获取商家所有有效订单
        //获取商家有效订单所有评分总和
        $where = array(
            'business_id' => $business_id,
            'status' => 6,
            'is_tui' => 0
        );
        $order_num = Db::name('order')
            ->where($where)
            ->count();
        $order_evaluate_sum = Db::name('order')
            ->where($where)
            ->sum('evaluate');
        $goods_evaluate = sprintf("%.1f", $order_evaluate_sum / $order_num);
        Db::name('business')->update(
            [
                'id' => $business_id,
                'evaluate' => $goods_evaluate
            ]
        );
    }

    //增加经验
//    public function addExperience($experience_count = 2, $desc = '用户签到')
//    {
//        //经验流水
//        $insert_data = array(
//            'member_id' => $this->memberId,
//            'type' => 1,
//            'count' => $experience_count,
//            'create_time' => time(),
//            'desc' => $desc
//        );
//        Db::name('member_experience')->insertGetId($insert_data);
//        Db::name('member')
//            ->where('id', '=', $this->memberId)
//            ->setInc('experience', $experience_count);
//        setUserLevel($this->memberId, $this->memberInfo['experience'], $experience_count, $this->memberInfo['level']);
//    }

    //增加减少积分
    public function addFraction($fraction_count = 2, $desc = '用户签到', $type = 1, $is_count = 1, $object_cate = '', $object_id = '', $create_id = '')
    {
        $insert_data = array(
            'member_id' => $this->memberId,
            'create_time' => time(),
            'count' => $fraction_count,
            'sign_time' => date('Y-m-d', time()),
            'desc' => $desc,
            'type' => $type,
            'is_count' => $is_count,
            'object_cate' => $object_cate,
            'object_id' => $object_id,
            'create_id' => $create_id,
        );
        Db::name('fraction_record')->insertGetId($insert_data);
        if ($is_count == 1) {
            Db::name('member')
                ->where('id', '=', $this->memberId)
                ->setInc('fraction', $fraction_count);
        } else {
            Db::name('member')
                ->where('id', '=', $this->memberId)
                ->setDec('fraction', $fraction_count);
        }
    }

    //订单退款
    public function refund()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];//订单id
        $tui_result = $data['tui_result'];
        $order_info = Db::name('order')->where('id', $order_id)->find();
        if (!$order_info) {
            msg(-1, '当前订单不存在', '');
        }
        if ($order_info['status'] != 2) {
            msg(-1, '当前订单不可退款', '');
        }
        //时间限制 待取货限制 返回钱 更新订单 更新优惠券
        $tui_time = config('site.tui_time') ? config('site.tui_time') * 60 : 15 * 60;
        if (time() - $order_info['pay_time'] >= $tui_time) {
            msg(-1, '时间已超过退款时间规定', '');
        }
        //qu_time_start
        $tui2_time = config('site.tui_qu_hour') ? config('site.tui_qu_hour') * 3600 : 5 * 3600;

        if (time() + $tui2_time >= $order_info['qu_time_end']) {
            msg(-1, '取货时间已超过规定', '');
        }
        Db::startTrans();
        try {
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $result = $app->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['pay_money'] * 100, $order_info['pay_money'] * 100, [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => '订单退款',
            ]);
            tuikuan($order_info, $order_id, $tui_result);
            Db::commit();
            msg(0, '修改成功', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }

    }

    public function userRole()
    {
        //1 商家 2员工 0 正常
        msg($this->role, '查询成功', $this->role);
    }

    //查看消息开启列表
    public function getMsgSwitchList()
    {
        $switch = Db::name('message_switch')->where([
            'member_id' => $this->memberId,
        ])->find();
        if ($switch) {
            msg(0, '查询成功', $switch);
        } else {
            Db::startTrans();
            try {
                $data_insert = array(
                    'member_id' => $this->memberId,
                    'is_all' => 1,
                    'is_system' => 1,
                    'is_qiandao' => 1,
                    'is_reply' => 1,
                    'is_coupon' => 1,
                );
                $data_id = Db::name('message_switch')->insertGetId($data_insert);
                $data_insert['id'] = $data_id;
                Db::commit();
                msg(0, '查询成功', $data_insert);
            } catch (\Exception $e) {
                Db::rollback();
                msg(-1, $e->getMessage(), '');
            }
        }
    }

    //设置消息是否开启
    public function setMsgSwitch()
    {
        $data = $this->request->param();
        $switch = Db::name('message_switch')->where([
            'member_id' => $this->memberId,
        ])->find();
        Db::startTrans();
        try {
            $where[] = ['member_id', '=', $this->memberId,];
            switch ($data['type']) {
                case 1:
                    $update = array(
                        'is_all' => $data['is_open'],
                        'is_system' => $data['is_open'],
                        'is_qiandao' => $data['is_open'],
                        'is_coupon' => $data['is_open'],
                        'is_reply' => $data['is_open']
                    );
                    Db::name('message_switch')->where($where)->update($update);
                    break;
                case 2:
                    $update = array(
                        'is_system' => $data['is_open']
                    );
                    Db::name('message_switch')->where($where)->update($update);
                    break;
                case 3:
                    $update = array(
                        'is_qiandao' => $data['is_open']
                    );
                    Db::name('message_switch')->where($where)->update($update);
                    break;
                case 4:
                    $update = array(
                        'is_coupon' => $data['is_open']
                    );
                    Db::name('message_switch')->where($where)->update($update);
                    break;
                case 5:
                    $update = array(
                        'is_reply' => $data['is_open']
                    );
                    Db::name('message_switch')->where($where)->update($update);
                    break;
                default:
                    msg(-1, '请输入正确值', 1);
            }
            $switch = Db::name('message_switch')->where([
                'member_id' => $this->memberId,
            ])->find();
            if ($switch['is_system'] == $switch['is_qiandao'] && $switch['is_qiandao'] == $switch['is_coupon'] && $switch['is_coupon'] == $switch['is_reply']) {
                $update2['is_all'] = $switch['is_system'];
            } else {
                $update2['is_all'] = 0;
            }
            Db::name('message_switch')->where($where)->update($update2);
            Db::commit();
            msg(0, '查询成功', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function msgSend()
    {
        $user_list = Db::name('member')->where([
            ['openid', '<>', null]
        ])->select();
        foreach ($user_list as $k => $v) {
            $insert_data = array(
                ''
            );
        }
    }

    public function wuya()
    {
        //    return 8:30-12:40;
    }

    //预售提醒
    public function preSale()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id'],
                'create_time' => time()
            );
            $result = Db::name('presale')->insertGetId($insert_data);
            Db::commit();
            msg(0, '查询成功', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //发送消息通知
    //购物后给服务站发送微信消息
    public function sendOrderXcxMessage()
    {
        $data = $this->request->param();
        try {
            $order_no = $data['order_no'];//订单编号
            //获取订单信息
            $order_info = Db::name('order')->where('order_no', $order_no)->find();
            $goods_info = Db::name('goods')->find($order_info['goods_id']);
//            dump($order_info);
//            die;
            //获取商家信息
            $business_info = Db::name('business')->find($order_info['business_id']);
            $bindMember = Db::name('member')->find($business_info['member_id']);
            $config = [
                'app_id' => config('wechat.appID'),
                'secret' => config('wechat.AppSecret'),
            ];
            $app = Factory::miniProgram($config);
            $send_data = [
                'template_id' => '-YwO1M5KHTIqYnw9yaCsoV41AS5GCZwPdkqoJrGxvuY', // 所需下发的订阅模板id
                'touser' => $bindMember['openid'],     // 接收者（用户）的 openid
                'page' => 'pages1/order/orderManage/orderManage?stater=2',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [
                    'thing1' => [
                        'value' => $goods_info['name'],
                    ],
                    'character_string4' => [
                        'value' => $order_info['order_no'],
                    ],
                    'thing13' => [
                        'value' => $this->memberInfo['nickname'],
                    ],
                    'phone_number11' => [
                        'value' => $this->memberInfo['mobile'],
                    ],
                ],
            ];
            $data = $app->subscribe_message->send($send_data);
            msg(0, '发送完成', $data);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }

    }

    public function employLevel()
    {

        $employ = Db::name('employ')->where([
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->find();
        if (!$employ) {
            msg(-1, '当前不是员工', '');
        }
        msg(0, '查询完成', $employ['role']);
    }
}

